package server;

import java.nio.charset.Charset;
import java.nio.charset.CharsetEncoder;

import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolEncoderAdapter;
import org.apache.mina.filter.codec.ProtocolEncoderOutput;

public class MessageEncoder extends ProtocolEncoderAdapter {
	private CharsetEncoder	encoder;

	public MessageEncoder() {
		Charset charset = Charset.forName("UTF-8");
		encoder = charset.newEncoder();
	}

	public void encode(IoSession session, Object message, ProtocolEncoderOutput out) throws Exception {
		IoBuffer buffer = IoBuffer.allocate(4);
		buffer.setAutoExpand(true);
		buffer.putString(((Message) message).toString(), encoder);
		buffer.flip();
		out.write(buffer);
	}
}
